<template>
  <div class="app-container">
    <div class="todo-management">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2>待办任务</h2>
        <p>管理您的待办任务，及时处理重要通知</p>
      </div>

      <!-- 统计卡片 -->
      <!-- <div class="stats-cards">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon unread">
                <i class="el-icon-s-order"></i>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ unreadCount }}</div>
                <div class="stat-label">未读任务</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon total">
                <i class="el-icon-document"></i>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ todoList.length }}</div>
                <div class="stat-label">总任务数</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon read">
                <i class="el-icon-check"></i>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ readTodoList.length }}</div>
                <div class="stat-label">已读任务</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card">
              <div class="stat-icon today">
                <i class="el-icon-time"></i>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ todayTodoCount }}</div>
                <div class="stat-label">今日新增</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div> -->

      <!-- 操作栏 -->
      <div class="operation-bar">
        <el-button type="success" @click="markAllAsRead" :disabled="!hasUnread">
          <i class="el-icon-check"></i>
          {{ isManager ? '全部标记已读（主管）' : '全部标记已读' }}
        </el-button>
        <el-button type="warning" @click="batchMarkAsRead" :disabled="selectedTodos.length === 0">
          <i class="el-icon-check"></i>
          批量标记已读
        </el-button>
        <el-button type="danger" @click="batchDelete" :disabled="selectedTodos.length === 0">
          <i class="el-icon-delete"></i>
          批量删除
        </el-button>
        <el-button type="info" @click="refreshData">
          <i class="el-icon-refresh"></i>
          刷新
        </el-button>
      </div>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="任务标题">
            <el-input v-model="searchForm.title" placeholder="请输入任务标题" clearable></el-input>
          </el-form-item>
          <el-form-item label="任务类型">
            <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
              <el-option label="订单预警" value="ORDER_WARNING"></el-option>
              <el-option label="考核预警" value="SCORE_WARNING"></el-option>
              <el-option label="白单预警" value="WHITE_ORDER_WARNING"></el-option>
              <el-option label="蓝单预警" value="BLUE_ORDER_WARNING"></el-option>
            </el-select>
          </el-form-item>
          <!-- 阅读状态筛选已移除，待办页面只显示未读数据 -->
          <el-form-item>
            <el-button type="primary" @click="searchTodos">
              <i class="el-icon-search"></i>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <i class="el-icon-refresh-left"></i>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>


      <!-- 任务列表 -->
      <div class="todo-list">
        <el-table
          :data="filteredTodoList"
          v-loading="loading"
          @selection-change="handleSelectionChange"
          stripe
          border
          style="width: 100%"
        >
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column prop="alertTitle" label="任务标题" min-width="200">
            <template slot-scope="scope">
              <div class="task-title">
                <i :class="getTaskIcon(scope.row.alertType)" class="task-icon"></i>
                <span :class="{ 'unread-title': !scope.row.isRead }">{{ scope.row.alertTitle }}</span>
                <el-tag v-if="!scope.row.isRead" type="danger" size="mini">未读</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="alertContent" label="任务内容" min-width="300" show-overflow-tooltip>
            <template slot-scope="scope">
              <div class="task-content">
                {{ scope.row.alertContent }}
                <div v-if="scope.row.problemUserName" class="problem-user">
                  <i class="el-icon-user"></i>
                  <span>问题人员：{{ scope.row.problemUserName }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="alertType" label="任务类型" width="120" align="center">
            <template slot-scope="scope">
              <el-tag :type="getTaskTypeColor(scope.row.alertType)" size="small">
                {{ getTaskTypeText(scope.row.alertType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="160" align="center">
            <template slot-scope="scope">
              <div class="time-info">
                <div>{{ formatDate(scope.row.createTime) }}</div>
                <div class="time-ago">{{ formatTimeAgo(scope.row.createTime) }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="140" align="center" fixed="right">
            <template slot-scope="scope">
              <div class="action-buttons">
                <el-tooltip v-if="!scope.row.isRead" content="标记已读" placement="top">
                  <el-button size="mini" type="success" plain circle icon="el-icon-check" @click="markAsRead(scope.row)" />
                </el-tooltip>
                <el-tooltip content="查看详情" placement="top">
                  <el-button size="mini" type="primary" plain circle icon="el-icon-view" @click="viewDetail(scope.row)" />
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button size="mini" type="danger" plain circle icon="el-icon-delete" @click="deleteTodo(scope.row)" />
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 任务详情对话框 -->
    <el-dialog
      title="任务详情"
      :visible.sync="detailDialogVisible"
      width="600px"
    >
      <div v-if="selectedTodo" class="task-detail">
        <div class="detail-header">
          <h3>{{ selectedTodo.alertTitle }}</h3>
          <el-tag :type="getTaskTypeColor(selectedTodo.alertType)">
            {{ getTaskTypeText(selectedTodo.alertType) }}
          </el-tag>
        </div>
        <div class="detail-content">
          <p>{{ selectedTodo.alertContent }}</p>
          <div v-if="selectedTodo.problemUserName" class="problem-user-info">
            <i class="el-icon-user"></i>
            <span>问题人员：{{ selectedTodo.problemUserName }}</span>
          </div>
        </div>
        <div class="detail-meta">
          <div class="meta-item">
            <span class="label">创建时间：</span>
            <span>{{ formatDate(selectedTodo.createTime) }}</span>
          </div>
          <div class="meta-item">
            <span class="label">状态：</span>
            <el-tag :type="selectedTodo.isRead ? 'success' : 'danger'">
              {{ selectedTodo.isRead ? '已读' : '未读' }}
            </el-tag>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="selectedTodo && !selectedTodo.isRead" type="primary" @click="markAsRead(selectedTodo)">
          标记已读
        </el-button>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'

export default {
  name: 'TodoManagement',
  data() {
    return {
      loading: false,
      selectedTodos: [],
      searchForm: {
        title: '',
        type: null
      },
      detailDialogVisible: false,
      selectedTodo: null
    }
  },
  computed: {
    ...mapGetters([
      'todo/todoList',
      'todo/unreadCount',
      'todo/unreadTodoList',
      'todo/readTodoList',
      'todo/hasUnread'
    ]),
    todoList() {
      return this['todo/todoList']
    },
    unreadCount() {
      return this['todo/unreadCount']
    },
    unreadTodoList() {
      return this['todo/unreadTodoList']
    },
    readTodoList() {
      return this['todo/readTodoList']
    },
    hasUnread() {
      return this['todo/hasUnread']
    },
    isManager() {
      const roles = this.$store.getters.roles || []
      return roles.some(role => 
        role === 'ADMIN' || 
        role === 'SHOUQIANZHUGUAN' || 
        role === 'SHOUZHONGZHUGUAN' || 
        role === 'SHOUHOUZHUGUAN' || 
        role === 'JISHUZHUGUAN'
      )
    },
    todayTodoCount() {
      const today = new Date().toDateString()
      return this.todoList.filter(todo => {
        const todoDate = new Date(todo.createTime).toDateString()
        return todoDate === today
      }).length
    },
    filteredTodoList() {
      let list = [...this.todoList]
      
      if (this.searchForm.title) {
        list = list.filter(todo => 
          todo.alertTitle.toLowerCase().includes(this.searchForm.title.toLowerCase())
        )
      }
      
      if (this.searchForm.type) {
        list = list.filter(todo => todo.alertType === this.searchForm.type)
      }
      
      return list
    }
  },
  created() {
    this.loadTodoList()
  },
  mounted() {
    // 页面挂载完成
  },
  methods: {
    ...mapActions([
      'todo/fetchTodoList',
      'todo/markAsRead',
      'todo/batchMarkAsRead',
      'todo/markAllAsRead',
      'todo/batchMarkAllAsRead',
      'todo/removeTodo',
      'todo/batchRemoveTodo'
    ]),
    
    async loadTodoList() {
      this.loading = true
      try {
        // 传递搜索参数给API（isRead由store层默认设置为0）
        const params = {
          title: this.searchForm.title || undefined,
          type: this.searchForm.type || undefined
        }
        await this['todo/fetchTodoList'](params)
      } catch (error) {
        console.error('加载待办列表失败:', error)
        this.$message.error('加载待办列表失败: ' + error.message)
      } finally {
        this.loading = false
      }
    },
    
    async searchTodos() {
      // 重新加载数据，应用搜索条件
      await this.loadTodoList()
    },
    
    async resetSearch() {
      this.searchForm = {
        title: '',
        type: null
      }
      // 重置后重新加载数据
      await this.loadTodoList()
    },
    
    async markAsRead(todo) {
      try {
        await this['todo/markAsRead'](todo.id)
        this.$message.success('已标记为已读')
        if (this.detailDialogVisible) {
          this.detailDialogVisible = false
        }
      } catch (error) {
        this.$message.error('操作失败: ' + error.message)
      }
    },
    
    async batchMarkAsRead() {
      if (this.selectedTodos.length === 0) {
        this.$message.warning('请选择要标记的任务')
        return
      }
      
      try {
        const ids = this.selectedTodos.map(todo => todo.id)
        await this['todo/batchMarkAsRead'](ids)
        this.$message.success('批量标记成功')
        this.selectedTodos = []
      } catch (error) {
        this.$message.error('操作失败: ' + error.message)
      }
    },
    
    async markAllAsRead() {
      try {
        if (this.isManager) {
          // 主管：不传userId参数，让后端自动查询下属
          const result = await this['todo/markAllAsRead']()
          this.$message.success(`全部标记完成，涉及 ${result.totalUsers} 个用户`)
        } else {
          // 员工：传自己的userId参数
          const currentUserId = this.$store.getters.id
          await this['todo/markAllAsRead'](currentUserId)
          this.$message.success('全部标记为已读')
        }
      } catch (error) {
        this.$message.error('操作失败: ' + error.message)
      }
    },
    
    async deleteTodo(todo) {
      try {
        await this.$confirm('确定要删除这个任务吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await this['todo/removeTodo'](todo.id)
        this.$message.success('删除成功')
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败: ' + error.message)
        }
      }
    },
    
    async batchDelete() {
      if (this.selectedTodos.length === 0) {
        this.$message.warning('请选择要删除的任务')
        return
      }
      
      try {
        await this.$confirm(`确定要删除选中的 ${this.selectedTodos.length} 个任务吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const ids = this.selectedTodos.map(todo => todo.id)
        await this['todo/batchRemoveTodo'](ids)
        this.$message.success('批量删除成功')
        this.selectedTodos = []
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败: ' + error.message)
        }
      }
    },
    
    viewDetail(todo) {
      this.selectedTodo = todo
      this.detailDialogVisible = true
    },
    
    handleSelectionChange(selection) {
      this.selectedTodos = selection
    },
    
    refreshData() {
      this.loadTodoList()
    },
    
    
    getTaskIcon(alertType) {
      const iconMap = {
        'ORDER_WARNING': 'el-icon-s-order',
        'SCORE_WARNING': 'el-icon-medal',
        'WHITE_ORDER_WARNING': 'el-icon-document',
        'BLUE_ORDER_WARNING': 'el-icon-warning'
      }
      return iconMap[alertType] || 'el-icon-info'
    },
    
    getTaskTypeText(alertType) {
      const typeMap = {
        'ORDER_WARNING': '订单预警',
        'SCORE_WARNING': '考核预警',
        'WHITE_ORDER_WARNING': '白单预警',
        'BLUE_ORDER_WARNING': '蓝单预警'
      }
      return typeMap[alertType] || '系统预警'
    },
    
    getTaskTypeColor(alertType) {
      const colorMap = {
        'ORDER_WARNING': 'warning',
        'SCORE_WARNING': 'danger',
        'WHITE_ORDER_WARNING': 'info',
        'BLUE_ORDER_WARNING': 'danger'
      }
      return colorMap[alertType] || 'info'
    },
    
    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return date.toLocaleString('zh-CN')
    },
    
    formatTimeAgo(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      const now = new Date()
      const diff = now - date
      
      if (diff < 60000) {
        return '刚刚'
      } else if (diff < 3600000) {
        return `${Math.floor(diff / 60000)}分钟前`
      } else if (diff < 86400000) {
        return `${Math.floor(diff / 3600000)}小时前`
      } else {
        return `${Math.floor(diff / 86400000)}天前`
      }
    },
    
    async refreshData() {
      // 刷新数据，保持当前搜索条件
      await this.loadTodoList()
      this.$message.success('数据已刷新')
    }
  }
}
</script>

<style lang="scss" scoped>
.todo-management {
  .page-header {
    margin-bottom: 20px;
    
    h2 {
      margin: 0 0 8px 0;
      color: #303133;
    }
    
    p {
      margin: 0;
      color: #606266;
      font-size: 14px;
    }
  }
  
  .stats-cards {
    margin-bottom: 20px;
    
    .stat-card {
      background: #fff;
      border-radius: 8px;
      padding: 20px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      display: flex;
      align-items: center;
      
      .stat-icon {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;
        
        i {
          font-size: 24px;
          color: #fff;
        }
        
        &.unread {
          background: linear-gradient(135deg, #f56c6c, #ff8a80);
        }
        
        &.total {
          background: linear-gradient(135deg, #409eff, #66b3ff);
        }
        
        &.read {
          background: linear-gradient(135deg, #67c23a, #85ce61);
        }
        
        &.today {
          background: linear-gradient(135deg, #e6a23c, #f0c78a);
        }
      }
      
      .stat-content {
        .stat-number {
          font-size: 28px;
          font-weight: bold;
          color: #303133;
          margin-bottom: 4px;
        }
        
        .stat-label {
          font-size: 14px;
          color: #909399;
        }
      }
    }
  }
  
  .operation-bar {
    margin-bottom: 20px;
    
    .el-button {
      margin-right: 10px;
    }
  }
  
  .search-bar {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  
  .todo-list {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    
    .task-title {
      display: flex;
      align-items: center;
      
      .task-icon {
        margin-right: 8px;
        font-size: 16px;
        color: #409eff;
      }
      
      .unread-title {
        font-weight: bold;
        color: #303133;
      }
    }
    
    .task-content {
      .problem-user {
        margin-top: 8px;
        padding: 4px 8px;
        background: #f0f9ff;
        border: 1px solid #b3d8ff;
        border-radius: 4px;
        font-size: 12px;
        color: #409eff;
        
        i {
          margin-right: 4px;
        }
      }
    }
    
    .time-info {
      .time-ago {
        font-size: 12px;
        color: #909399;
        margin-top: 4px;
      }
    }
    
    .action-buttons {
      .el-button {
        margin: 0 2px;
      }
    }
  }
  
  .task-detail {
    .detail-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      padding-bottom: 12px;
      border-bottom: 1px solid #e4e7ed;
      
      h3 {
        margin: 0;
        color: #303133;
      }
    }
    
    .detail-content {
      margin-bottom: 16px;
      
      p {
        margin: 0 0 12px 0;
        line-height: 1.6;
        color: #606266;
      }
      
      .problem-user-info {
        padding: 8px 12px;
        background: #f0f9ff;
        border: 1px solid #b3d8ff;
        border-radius: 4px;
        color: #409eff;
        font-size: 14px;
        
        i {
          margin-right: 6px;
        }
      }
    }
    
    .detail-meta {
      .meta-item {
        display: flex;
        margin-bottom: 8px;
        
        .label {
          width: 80px;
          color: #909399;
        }
      }
    }
  }
}
</style>
